﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using UMC.Net;
using UMC.Web;
using UMC.Wiki.Entities;
using System.Collections;

namespace UMC.Wiki.Activities
{



    class SubjectSaveActivity : WebActivity
    {

        public static void Dashboard(UMC.Security.Identity user, Subject sub, Guid appkey)
        {
            var uPId = Utility.UInt64Parse(user.Id.Value);
            var project = DataFactory.Instance().Project(uPId);

            if (project == null)
            {
                var team = new Project();
                team.ModifiedTime = DateTime.Now;


                team.Id = uPId;
                team.user_id = user.Id;
                team.Code = UMC.Data.Utility.Parse36Encode(Utility.IntParse(uPId)[1]);
                team.CreationTime = DateTime.Now;
                team.Caption = user.Alias;
                team.Sequence = 0;
                team.SubjectTotal = 1;
                team.MemberTotal = 1;
                team.AppKey = appkey;
                sub.project_id = team.Id;


                DataFactory.Instance().Put(team);
                Web.WebResource.Instance().Transfer(new Uri("https://res.apiumc.com/UserResources/app/zhishi-icon.jpg"), uPId, 1);
                var p = new ProjectItem()
                {
                    Id = UMC.Data.Utility.NewId(),
                    Caption = "知识录",
                    Code = "Wiki",
                    CreationTime = DateTime.Now,
                    project_id = team.Id,
                    Hide = false,
                    Sequence = 0,
                    SubjectTotal = 1,
                    user_id = user.Id,
                };
                DataFactory.Instance().Put(p);
                sub.project_item_id = p.Id;

                var portfolio2 = new Portfolio()
                {
                    Id = UMC.Data.Utility.NewId(),
                    Caption = "随笔",
                    SubjectTotal = 1,
                    CreationTime = DateTime.Now,
                    Sequence = 0,
                    user_id = user.Id,
                    project_id = team.Id,
                    project_item_id = p.Id
                };
                DataFactory.Instance().Put(portfolio2);
                sub.portfolio_id = portfolio2.Id;
                DataFactory.Instance().Put(new ProjectMember { project_id = team.Id, CreationTime = DateTime.Now, Alias = user.Alias, AuthType = WebAuthType.Admin, user_id = user.Id });


                DataFactory.Instance().Put(new Attention
                {
                    Id = user.Id,
                    SubjectTotal = ((DataFactory.Instance().Attention(user.Id.Value) ?? new Attention { Id = user.Id }).SubjectTotal ?? 0) + 1
                });

                return;
            }
            var projectItem = DataFactory.Instance().ProjectItem(new Project { Id = project.Id.Value })[0];

            sub.project_id = project.Id;
            sub.project_item_id = projectItem.Id;

            var portfolio = DataFactory.Instance().Portfolio(projectItem)[0];

            sub.portfolio_id = portfolio.Id;

            DataFactory.Instance().Put(new Project
            {
                Id = project.Id,
                SubjectTotal = (project.SubjectTotal ?? 0) + 1
            });
            DataFactory.Instance().Put(new ProjectItem
            {
                Id = projectItem.Id,
                SubjectTotal = (projectItem.SubjectTotal ?? 0) + 1
            });
            DataFactory.Instance().Put(new Portfolio
            {
                Id = portfolio.Id,
                SubjectTotal = (portfolio.SubjectTotal ?? 0) + 1
            });
            var ax = DataFactory.Instance().Attention(user.Id.Value) ?? new Attention { Id = user.Id };
            DataFactory.Instance().Put(new Attention
            {
                Id = user.Id,
                SubjectTotal = (ax.SubjectTotal ?? 0) + 1
            });

        }

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var Id = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("Id", g =>
            {
                return this.DialogValue("none");
            }));
            var ui = this.AsyncDialog("UI", "none");
            var Next = this.AsyncDialog("Next", "none");
            var Url = this.AsyncDialog("Url", g =>
            {
                this.Context.UIEvent("UI.Submit", ui, new Web.UIClick(request, "Id", Id.ToString(), "UI", ui, "Next", Next)
                 , true);

                return this.DialogValue("none");
            });

            var sub = DataFactory.Instance().Subject(Id.Value);
            var user = this.Context.Token.Identity();
            if (user.IsAuthenticated == false)
            {
                this.Context.Send("Login", true);
            }


            var ContentType = "html";
            Array celss;
            var content = new Uri(Url).WebRequest().Get(out var _);
            if (content.StartsWith("{") == false && content.StartsWith("[") == false)
            {
                ContentType = "markdown";
                var cells = Data.Markdown.Transform(content);
                var dlist = new ArrayList();
                foreach (var d in cells)
                {
                    dlist.Add(new WebMeta().Put("type", d.Type).Put("value", d.Data).Put("format", d.Formats).Put("style", d.Style).GetDictionary());

                }
                celss = dlist.ToArray();
            }
            else
            {
                var conts = Data.JSON.Deserialize(content) as Array;
                content = null;
                var cont = conts.GetValue(1) as Hashtable;

                celss = cont["data"] as Array;
            }
            if (sub == null)
            {
                var Title = String.Format("{0:yyyy-MM-dd hh:mm}", DateTime.Now);
                if (celss.Length > 0)
                {

                    var pom = celss.GetValue(0) as Hashtable;
                    var Cname = pom["type"] as string ?? "";
                    if (Cname == "CMSText")
                    {
                        var format = pom["format"] as Hashtable;
                        if (format == null)
                        {
                            format = (pom["format"] as WebMeta).GetDictionary();
                        }
                        var value = pom["value"] as Hashtable;
                        if (value == null)
                        {
                            value = (pom["value"] as WebMeta).GetDictionary();
                        }
                        if (value == null)
                        {
                            value = (pom["value"] as WebMeta).GetDictionary();
                        }
                        if (format == null)
                        {
                            format = new Hashtable();
                        }
                        if (value == null)
                        {
                            Title = "未设置标题";
                        }
                        else
                        {
                            Title = UMC.Data.Utility.Format((format["text"] as string) ?? "{text}", value);
                        }
                    }

                }

                sub = new Subject()
                {
                    Title = Title,
                    IsPicture = false,
                    Id = Id,
                    Url = Url,
                    LastDate = DateTime.Now,
                    last_user_id = user.Id,
                    CreationTime = DateTime.Now,
                    Poster = user.Alias,
                    user_id = user.Id,
                    Favs = 0,
                    Look = 0,
                    Reply = 0,
                    Score = 0,
                    Seq = 0,
                    TipOffs = 0,
                    IsComment = false,
                    Status = -1
                };
                sub.Code = UMC.Data.Utility.Parse36Encode(Utility.IntParse(sub.Id.Value)[1]);
                Dashboard(user, sub, this.Context.AppKey ?? Guid.Empty);
                DataFactory.Instance().Put(sub);

                if (String.Equals(ContentType, "markdown"))
                {
                    Next = "Subject";
                }
            }
            var webr = UMC.Web.WebResource.Instance();
            var wSomain = webr.Provider["domain"] ?? "localhost";

            var domain = $"{this.Context.Request.Url.Scheme}://{wSomain}/";

            var list = new Dictionary<String, Uri>();
            //var mains = new List<String>();
            var sp = UMC.Data.Utility.TimeSpan();
            foreach (var o in celss)
            {
                var pom = o as Hashtable;
                var Cname = pom["type"] as string ?? "";

                switch (Cname)
                {
                    case "CMSImage":
                        var value = pom["value"] as Hashtable;
                        if (value == null)
                        {
                            value = (pom["value"] as WebMeta).GetDictionary();
                        }
                        var src = new Uri(value["src"] as string);
                        if (domain.Contains(src.Host) == false)
                        {
                            if (src.Host.StartsWith("www.365lu.cn"))
                            {
                                value["src"] = $"{domain}{src.PathAndQuery}";
                            }
                            else
                            {
                                var jpg = ".jpg";
                                var ex = src.AbsolutePath.LastIndexOf(".");

                                if (ex > -1)
                                {
                                    jpg = src.AbsolutePath.Substring(ex);

                                }

                                var gk = new Guid(UMC.Data.Utility.MD5(src.AbsoluteUri));
                                var srcKey = $"UserResources/{sub.project_id ?? 0}/{gk}{jpg}";
                                value["src"] = domain + srcKey;
                                list[srcKey] = src;
                            }
                        }
                        break;
                }
            }

            DataFactory.Instance().Put(new SubjectContent
            {
                Id = Id.Value,
                ContentType = ContentType,
                Content = content,
                DataJSON = Data.JSON.Serialize(celss)
            });
            try
            {
                var em = list.GetEnumerator();
                while (em.MoveNext())
                {
                    webr.Transfer(em.Current.Value, em.Current.Key);

                }
            }
            catch (Exception ex)
            {
                UMC.Data.Utility.Error("Subject/image", ex.StackTrace);
            }

            this.Context.UIEvent("UI.Save", ui, new UMC.Web.WebMeta(), false);

            if (Next == "Subject")
            {
                this.Prompt("保存成功", false);
                this.Context.Send("Subject.Save", false);
                this.Context.Send(new UISectionBuilder(request.Model, "EditUI", new UMC.Web.WebMeta().Put("Id", Id))
                    .RefreshEvent("Subject.Save", "System.Image", "Subject.Content")
                        .Builder(), true);
            }
            else if (Next == "View")
            {
                this.Context.Send(new UISectionBuilder(request.Model, "UIMin", new UMC.Web.WebMeta().Put("Id", sub.Id))
                        .Builder(), true);
            }
            else
            {
                this.Prompt("保存成功", false);
                this.Context.Send("Subject.Content", true);
            }
        }

    }
}